package com.pms.web;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.pms.controller.BaseController;
import com.pms.core.CommonConstant;
import com.pms.entity.*;
import com.pms.entity.vo.AuthorityMenuTree;
import com.pms.entity.vo.MenuTree;
import com.pms.exception.R;
import com.pms.result.ObjectRestResponse;
import com.pms.service.*;
import com.pms.util.TreeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zyl
 * @since 2017-07-06
 */
@Controller
@RequestMapping("menu")
@Api(value = "菜单管理",description = "菜单管理")
public class BaseMenuController extends BaseController {
	@Autowired
    IBaseUserService baseUserService;
	@Autowired
    IBaseMenuService baseMenuService;
    @Autowired
    IBaseResourceAuthorityService baseResourceAuthorityService;
    @Autowired
    IBaseElementService baseElementService;
    @Autowired
    IBaseGroupService baseGroupService;
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public List<BaseMenu> list(String title) {
        EntityWrapper entityWrapper = new EntityWrapper();
        if(StringUtils.isNotBlank(title)){
            entityWrapper.eq("title",title);
        }
        List<BaseMenu> menuList = baseMenuService.selectList(null);
        return menuList;
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    public ObjectRestResponse<List<AuthorityMenuTree>> getMenuAuthority(@PathVariable int id){
        return new ObjectRestResponse().data(baseMenuService.selectById(id));
    }

    /**
     * 获取菜单权限树
     * @param title
     * @return
     */
    @RequestMapping(value = "/tree", method = RequestMethod.GET)
    @ResponseBody
    public List<MenuTree> getTree(String title, Long userId,Integer menuType) {
//        parameterIsNull(userId,"用户ID不能为空");
//        BaseUser user=baseUserService.selectById(userId);
//        if (user==null){throw  new RRException("用户信息不存在",400);}
        List<BaseMenu> BaseMenu=  baseMenuService.selectListTree();
        List<MenuTree>  MenuTree =getMenuTree(BaseMenu, CommonConstant.ROOT);
        return MenuTree;
    }


    @RequestMapping(value = "/all",method = RequestMethod.GET)
    @ResponseBody
    public List<BaseMenu> list(){
        List<BaseMenu> list = baseMenuService.selectList(new EntityWrapper<BaseMenu>());
        return list;
    }

    /**
     * 菜单树
     * @param parentId
     * @return
     */
    @RequestMapping(value = "/menuTree", method = RequestMethod.GET)
    @ResponseBody
    public R listMenu(Integer parentId) {
        List<MenuTree> trees = new ArrayList<MenuTree>();
        BaseMenu parent = baseMenuService.selectById(parentId);
        List<BaseMenu> menus = baseMenuService.selectList(new EntityWrapper<BaseMenu>().like("path",parent.getPath()).eq("id",parent.getId()));
        List<MenuTree> listMenuTree = getMenuTree(menus, parent.getId());
        return R.ok().put("date",listMenuTree);
    }

    /**
     * 权限树
     * @return
     */
    @RequestMapping(value = "/authorityTree", method = RequestMethod.GET)
    @ResponseBody
    public List<AuthorityMenuTree> listAuthorityMenu() {
        List<AuthorityMenuTree> trees = new ArrayList<AuthorityMenuTree>();
        AuthorityMenuTree node = null;
        for (BaseMenu menu : baseMenuService.selectList(null)) {
            node = new AuthorityMenuTree();
            node.setText(menu.getTitle());
            BeanUtils.copyProperties(menu, node);
            trees.add(node);
        }
        return TreeUtil.bulid(trees, CommonConstant.ROOT);
    }

    /**
     * 用户Id查询权限
     * @param parentId
     * @returnqw
     */
    @RequestMapping(value = "/user/authorityTree", method = RequestMethod.GET)
    @ResponseBody
    public List<MenuTree> listUserAuthorityMenu(Integer parentId){
        String companyCode = request.getHeader("X-Code");
        String username = request.getHeader("X-Name");;
        Long userId = baseUserService.getUserByUsername(username,companyCode).getId();

        return getMenuTree(baseMenuService.getUserAuthorityMenuByUserId(userId.intValue()),parentId);
    }

    @RequestMapping(value = "/system", method = RequestMethod.GET)
    @ResponseBody
    public R listUserAuthoritySystem() {
        String companyCode = request.getHeader("X-Code");
        String username = request.getHeader("X-Name");;
        Long userId = baseUserService.getUserByUsername(username,companyCode).getId();
        List<BaseMenu> menuList = baseMenuService.selectAuthoritySystemByUserId(userId.intValue());
        return R.ok().put("date",menuList);
    }


    /**
     * 菜单树
     * @param menus
     * @param root
     * @return
     */
    private List<MenuTree> getMenuTree(List<BaseMenu> menus, int root) {
        List<MenuTree> trees = new ArrayList<MenuTree>();
        for (BaseMenu menu : menus) {
            MenuTree node = new MenuTree();
            List<TreeNode> children=new ArrayList<TreeNode>();
            for (int i=0;i<menu.getBaseElement().size();i++){
                TreeNode tn=new TreeNode();
                if (menu.getBaseElement().get(i).getId()==null){
                    continue;
                }
                tn.setBaseElementId(Integer.valueOf(menu.getBaseElement().get(i).getId()));
                tn.setTitle(menu.getBaseElement().get(i).getName());
                tn.setId(menu.getId());
                tn.setParentId(Integer.valueOf(menu.getBaseElement().get(i).getMuentParentId()));
                children.add(tn);
                node.setChildren(children);
            }
            BeanUtils.copyProperties(menu, node);
            trees.add(node);
        }
        return TreeUtil.bulid(trees,root) ;
    }
    /**
     * 新增
     * @param entity
     * @return
     */
    @RequestMapping(value = "",method = RequestMethod.POST)
    @ResponseBody
    public ObjectRestResponse<BaseMenu> add(@RequestBody BaseMenu entity){
    if(StringUtils.isNotBlank(entity.getHref())){
        entity.setHref(entity.getHref());
        entity.setMenuType(entity.getMenuType());
        entity.setType("menu");
        baseMenuService.insert(entity);
        List<BaseGroup> as=baseGroupService.selectList(new EntityWrapper<BaseGroup>().eq("type",1));
        for (int x=0;x<as.size();x++){
            BaseResourceAuthority Resource=new BaseResourceAuthority();
            Resource.setResourceId(entity.getId().toString());
            Resource.setResourceType("menu");
            Resource.setAuthorityId(as.get(x).getId().toString());
            Resource.setAuthorityType("group");
            Resource.setCrtTime(new Date());
            Resource.setParentId("-1");
            baseResourceAuthorityService.insert(Resource);
        }
        List<BaseElement>  baseElementGets=new ArrayList<BaseElement>();
        //查看
        BaseElement baseElementGet =new BaseElement();
        baseElementGet.setCode(entity.getCode()+":view");
        baseElementGet.setType("uri");
        baseElementGet.setName("查看");
        baseElementGet.setUri("/"+entity.getHref());
        baseElementGet.setMenuId(entity.getId().toString());
        baseElementGet.setMethod("GET");
        baseElementGet.setCrtTime(new Date());
        baseElementGets.add(baseElementGet);
        //新增
        BaseElement baseElementadd =new BaseElement();
        baseElementadd.setCode(entity.getCode()+":btn_add");
        baseElementadd.setType("button");
        baseElementadd.setName("新增");
        baseElementadd.setUri("/"+entity.getHref());
        baseElementadd.setMenuId(entity.getId().toString());
        baseElementadd.setMethod("POST");
        baseElementadd.setCrtTime(new Date());
        baseElementGets.add(baseElementadd);
        //编辑
        BaseElement baseElementEdit =new BaseElement();
        baseElementEdit.setCode(entity.getCode()+":btn_edit");
        baseElementEdit.setType("button");
        baseElementEdit.setName("编辑");
        baseElementEdit.setUri("/"+entity.getHref());
        baseElementEdit.setMenuId(entity.getId().toString());
        baseElementEdit.setMethod("PUT");
        baseElementEdit.setCrtTime(new Date());
        baseElementGets.add(baseElementEdit);
        //删除
        BaseElement baseElementDel =new BaseElement();
        baseElementDel.setCode(entity.getCode()+":btn_del");
        baseElementDel.setType("button");
        baseElementDel.setName("删除");
        baseElementDel.setUri("/"+entity.getHref());
        baseElementDel.setMenuId(entity.getId().toString());
        baseElementDel.setMethod("DELETE");
        baseElementDel.setCrtTime(new Date());
        baseElementGets.add(baseElementDel);
        baseElementService.insertBatch(baseElementGets);
    }else{
        entity.setHref(null);
        baseMenuService.insert(entity);
        List<BaseGroup> as=baseGroupService.selectList(new EntityWrapper<BaseGroup>().eq("type",1));
        for (int x=0;x<as.size();x++){
            BaseResourceAuthority Resource=new BaseResourceAuthority();
            Resource.setResourceId(entity.getId().toString());
            Resource.setResourceType("menu");
            Resource.setAuthorityId(as.get(x).getId().toString());
            Resource.setAuthorityType("group");
            Resource.setCrtTime(new Date());
            Resource.setParentId("-1");
            baseResourceAuthorityService.insert(Resource);
        }

    }
        return new ObjectRestResponse<BaseMenu>().rel(true);
    }

    /**
     * 更改
     * @param entity
     * @return
     *
     */
    @RequestMapping(value = "/{id}",method = RequestMethod.PUT)
    @ResponseBody
    public ObjectRestResponse<BaseMenu> update(@RequestBody BaseMenu entity){
        if(StringUtils.isNotBlank(entity.getHref())){
            entity.setHref(entity.getHref());
//            baseElementService.delete(new EntityWrapper<BaseElement>().eq("id",entity.getId()));
//            List<BaseElement>  baseElementGets=new ArrayList<BaseElement>();
//            //查看
//            BaseElement  baseElementGet =new BaseElement();
//            baseElementGet.setCode(entity.getCode()+":view");
//            baseElementGet.setType("uri");
//            baseElementGet.setName("查看");
//            baseElementGet.setUri("/"+entity.getHref());
//            baseElementGet.setMenuId(entity.getId().toString());
//            baseElementGet.setMethod("GET");
//            baseElementGet.setCrtTime(new Date());
//            baseElementGets.add(baseElementGet);
//            //新增
//            BaseElement  baseElementadd =new BaseElement();
//            baseElementadd.setCode(entity.getCode()+":btn_add");
//            baseElementadd.setType("button");
//            baseElementadd.setName("新增");
//            baseElementadd.setUri("/"+entity.getHref());
//            baseElementadd.setMenuId(entity.getId().toString());
//            baseElementadd.setMethod("POST");
//            baseElementadd.setCrtTime(new Date());
//            baseElementGets.add(baseElementadd);
//            //编辑
//            BaseElement  baseElementEdit =new BaseElement();
//            baseElementEdit.setCode(entity.getCode()+":btn_edit");
//            baseElementEdit.setType("button");
//            baseElementEdit.setName("编辑");
//            baseElementEdit.setUri("/"+entity.getHref());
//            baseElementEdit.setMenuId(entity.getId().toString());
//            baseElementEdit.setMethod("PUT");
//            baseElementEdit.setCrtTime(new Date());
//            baseElementGets.add(baseElementEdit);
//            //删除
//            BaseElement  baseElementDel =new BaseElement();
//            baseElementDel.setCode(entity.getCode()+":btn_del");
//            baseElementDel.setType("button");
//            baseElementDel.setName("删除");
//            baseElementDel.setUri("/"+entity.getHref());
//            baseElementDel.setMenuId(entity.getId().toString());
//            baseElementDel.setMethod("DELETE");
//            baseElementDel.setCrtTime(new Date());
//            baseElementGets.add(baseElementDel);
//            baseElementService.insertBatch(baseElementGets);
        }else entity.setHref(null);
        entity.setType("menu");
        baseMenuService.updateById(entity);
        return new ObjectRestResponse<BaseMenu>().rel(true);
    }


    /**
     * 删除
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}",method = RequestMethod.DELETE)
    @ResponseBody
    public ObjectRestResponse<BaseMenu> update(@PathVariable int id){
        baseMenuService.deleteById (id);
        baseResourceAuthorityService.delete(new EntityWrapper<BaseResourceAuthority>().eq("resource_id",id));
        baseElementService.delete(new EntityWrapper<BaseElement>().eq("menu_id",id));
        return new ObjectRestResponse<BaseMenu>().rel(true);
    }




}
